var tas = document.getElementsByClassName('answers');
var data_to_send = [];
var last_saved_values = [];
var cms = [];

function canAnswer(form) {
    var dt = $(form).data('start-time');
    var min = $(form).data('duration');
    var start = moment(dt, 'MMMM D YYYY, h:mm a');
    var end = moment(dt, 'MMMM D YYYY, h:mm a').add(min, 'minutes');
    var now = moment();
    // console.log('start: ' + start.format());
    // console.log('end: ' + end.format());
    return now.isBetween(start, end);
}

function willDisplay(form) {
    var dt = $(form).data('start-time');
    var start = moment(dt, 'MMMM D YYYY, h:mm a');
    var now = moment();
    return now.isAfter(start);
}

function checkChanged() {
    for (var i=0, l=cms.length; i<l; i++) {
        var form = cms[i].getWrapperElement().parentNode;
        var update_btn = $(form).find("button[type='submit']");

        if ($(form).hasClass('js-amendment')) {
            continue;
        }

        if (canAnswer(form)) {
            cms[i].setOption('readOnly', false);
            update_btn.prop("disabled", false);
        }
        else {
            cms[i].setOption('readOnly', 'nocursor');
            update_btn.prop("disabled", true);
        }

        if (willDisplay(form)) {
            $(form).parentsUntil('div.exambor').parent().show();
        } else {
            $(form).parentsUntil('div.exambor').parent().hide();
        }

        if(last_saved_values[i] !== cms[i].getValue()) {
            $(form).find('label.hint').text('changed');
            // console.log($(form).find('label.hint').text());
        }
    }
}

function sendInput() {
    for (var i=0, l=cms.length; i<l; i++) {

        var form = cms[i].getWrapperElement().parentNode;
        if ($(form).hasClass('js-amendment')) {
            continue;
        }

        if(last_saved_values[i] !== cms[i].getValue()) {
            var lbl = $(form).find('label.hint');
            var answer_id = $(form).attr('ajax-answer-id');
            var content = cms[i].getValue();
            $.ajax({
              url: "/exam/update/answer/",
              method: 'POST',
              data: {
                content: content,
                answer_id: answer_id,
              },
              context: {
                lbl: lbl,
                content: content,
                i: i,
              },
              success: function( result ) {
                console.log(result);
                last_saved_values[this.i] = this.content;
                this.lbl.text(result.msg);
              }
            });
        }
    }
}

function onChange(cm, change) {
    // console.log(change);
    // console.log(cm.getInputField());
    // console.log(cm.getValue());
    // var form = cm.getWrapperElement().parentNode;
    // $(form).find('label.hint').text('changed');
}

function display_exam_not_ended() {
    for (var i=0, l=tas.length; i<l; i++) {
        tas[i].id = 'ta-' + i;
        last_saved_values.push(tas[i].value)
        var cm = CodeMirror.fromTextArea(tas[i], {
            mode: {name: "python",
                   version: 3,
                   singleLineStringErrors: false},
            lineNumbers: true,
            indentUnit: 4,
            matchBrackets: true,
        });

        cm.on("change", onChange);
        cms.push(cm);
    }

    var CHECK_INTERVAL = 500;
    setInterval(checkChanged, CHECK_INTERVAL);
    var SEND_INTERVAL = 3000;
    setInterval(sendInput, SEND_INTERVAL);
}

function display_exam_ended() {
    load_all_comments();
    prettyPrint(printprint_finished);
}

$(document).ready(function() {
    if ($.py.is_exam_ended) {
        display_exam_ended();
    }
    else {
        display_exam_not_ended();
    }
})